import React, {createContext, useEffect, useRef} from 'react';
import LogFactory from "log/LogFactory";
import {Link, Outlet, useLocation, useNavigate} from "react-router-dom";
import {Report} from "type/entity/Report";
import {App, Button, Card, Divider, Flex, Space, Statistic, Table} from "antd";
import reportDetailColumns from "columns/ReportDetailColumns";
import {CreditCardOutlined, DiffOutlined, CloudSyncOutlined, CloseOutlined} from "@ant-design/icons";
import TableToolbar from "common/table/TableToolbar";
import {useAppDispatch, useAppSelector} from "storage/redux/hook";
import {fetchDetailItemList, fetchReportDetailList, updateReportId} from "storage/redux/reducer/reportDetail";
import RequestStatus from "storage/redux/RequestStatus";
import {fetchUpdateReportTotalAmount} from "storage/redux/reducer/report";


const log = LogFactory.getLogger("ReportDetailComponent");
export const ReportDetailContext = createContext<React.MutableRefObject<number> | null>(null);
const ReportDetailComponent = () => {
    const report = {...useLocation().state as Report};
    const refAmount = useRef<number>(0);
    const state = useAppSelector(s => s.reportDetail);
    const dispatch = useAppDispatch();
    const { message } = App.useApp();
    const [ isSync, setIsSync ] = React.useState<boolean>(false);
    const navigate = useNavigate();

    useEffect(() => {
        dispatch(fetchReportDetailList(report.id));
        dispatch(updateReportId(report.id));
    }, []);

    if (state.detailItems.length <= 0){
        dispatch(fetchDetailItemList());
    }

    log.debug("report", refAmount, report);
    useEffect(() => {
        const timeoutId = setTimeout(() => {
            // log.debug("reportID: ", report.id, "state.ID: ", state.reportId);
            // 添加结束后修改report中的总金额
            // 将总金额和总条目同步到服务器
            // 1. 页面为http://localhost:3000/nav/record/report/detail
            // detail 结尾endwith
            // 2. report的总金额和 页面计算的不一致
            // 满足哲两个条件
            log.debug("准备自动同步总金额和总条目:  report.totalAmount: ", report.totalAmount);
            log.debug("准备自动同步总金额和总条目:  state.totalMoney: ", state.totalMoney);
            if (state.requestStatus === RequestStatus.SUCCESS && window.location.pathname.endsWith("/detail") && report.totalAmount !== state.totalMoney){
                if (state.totalMoney === refAmount.current){
                    log.debug("金额一致,不需要同步");
                    return;
                }
                log.debug("执行报销单金额和条目数据同步");
                report.totalAmount = state.totalMoney;
                refAmount.current = state.totalMoney;
                dispatch(fetchUpdateReportTotalAmount({reportId: report.id, amount: state.totalMoney, count: state.data.length}))
                    .unwrap()
                    .then(res => {
                        if (res.success){
                            message.success("自动同步报销记录成功");
                        }else {
                            message.warning("同步报销记录失败,请手动同步");
                        }
                    });
            }
        }, 800);
        return () => {
            log.debug("clearTimeout: ", timeoutId);
            clearTimeout(timeoutId);
        };
    });
    /** 刷新页面数据 */
    const refresh = async () => {
        await dispatch(fetchReportDetailList(report.id));
        message.success("刷新数据成功");
    };

    const syncData = async () => {
            log.debug("手动同步数据:  state.totalMoney: ", state.totalMoney);
            setIsSync(true);
            await dispatch(fetchUpdateReportTotalAmount({reportId: report.id, amount: state.totalMoney, count: state.data.length}));
            setIsSync(false);
    };

    return (
       <ReportDetailContext.Provider value={refAmount}>
           <Outlet/>
           <Card title={"报销记录详情"} extra={<Link to={".."}>报销单列表</Link>}>
               <TableToolbar title={"报销单"} info={report.id} skipState={report} refresh={refresh}/>
               <Flex style={{ paddingInline: "5px" }} justify={"space-between"}>
                   <Space size={40} style={{ userSelect: "none" }}>
                       <Statistic title={"report总金额"} value={report.totalAmount} precision={2}/>
                       <Statistic title={"refAmount"} value={refAmount.current} precision={2}/>
                       <Statistic title={"页面计算总金额"} value={state.totalMoney} precision={2}/>
                   </Space>
                   <Space size={15}>
                       <Button disabled={state.data.length > 0} type={"primary"} danger size={"middle"} icon={<CloseOutlined />}>删除报销单</Button>
                       <Button type={"primary"} size={"middle"} icon={<CreditCardOutlined />} onClick={() => navigate("board", {state: report })}>数据看板</Button>
                       <Button type={"primary"} size={"middle"} icon={<DiffOutlined />} onClick={() => navigate("item", {state: report })}>报销项目</Button>
                       <Button type={"primary"} size={"middle"} icon={<CloudSyncOutlined />} onClick={syncData} loading={isSync}>同步数据</Button>
                   </Space>
               </Flex>
               <Divider/>
               <Table
                   scroll={{x: 800}}
                   columns={reportDetailColumns}
                   dataSource={state.data}
               />
           </Card>
       </ReportDetailContext.Provider>
    );
};

export default ReportDetailComponent;